﻿using System;
using System.Web.Mvc;
using CRM.Database.Model;
using DevExpress.Web.Mvc;
using TrainingRequest.Models;
//using Contacts = CRM.Database.Model.Contacts;
//using DB = TrainingRequest.Models.DB;
//using TrainingsRequestsExt = TrainingRequest.Models.TrainingsRequestsExt;


namespace TrainingRequest.Controllers
{
    public class TCController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        #region TrainingsSchedules

        [Authorize]
        public ActionResult TrainingsSchedules()
        {
            var schedules = new CRM.Database.Model.TrainingsSchedulesCollection();
            return View(schedules.OutsideSchedulesTable);
            //return View(DB.GetTrainingsSchedulesTable());
        }

        public ActionResult TrainingsSchedulesPartial()
        {
            var schedules = new CRM.Database.Model.TrainingsSchedulesCollection();
            return PartialView("TrainingsSchedulesPartial", schedules.OutsideSchedulesTable);
            //return PartialView("TrainingsSchedulesPartial", DB.GetTrainingsSchedulesTable());
        }

        #endregion

        #region TrainingsRequests

        /// <summary>
        /// создание новой плановой заявки
        /// </summary>
        /// <param name="scheduleId"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        [Authorize]
        public ActionResult TrainingsPlannedRequestCreate(int scheduleId, string username)
        {

            var requestExt = new CRM.Database.Model.TrainingsRequestsExt { Request = { IdTrainingsSchedule = scheduleId } };
            //var loginName = Request.LogonUserIdentity.Name;
            var contactsCol = new ContactsCollection();
            var contact = contactsCol.GetContactByLoginName(username);
            //var contact = DB.GetContactByLoginName(username);
            
            //временный код
            contact = (CRM.Database.Model.Contacts)contactsCol.GetItemById(16141);
            //временный код - конец

            if(contact!=null)
            {
                if (contact.LegalEntities != null)
                    if (contact.LegalEntities.Customers != null)
                    {
                        if (contact.LegalEntities.Name != null)
                            requestExt.Request.Company = contact.LegalEntities.Name;
                        requestExt.Request.ContactName = contact.Name;
                        requestExt.Request.ContactPhone = contact.Phone;
                        requestExt.Request.ContactEmail = contact.Email;
                        requestExt.Request.IdContact = contact.IdContact;
                        requestExt.Request.IdLegalEntity = contact.IdLegalEntity;
                        requestExt.Request.IdCustomer = contact.LegalEntities.Customers.IdCustomer;
                        var key = InternalClasses.TrainingsRequestsExtDictionary.Count;
                        requestExt.Key = key;
                        InternalClasses.TrainingsRequestsExtDictionary.Add(key, requestExt);

                        return View(requestExt);
                    }
            }
            return RedirectToAction("TrainingsSchedules");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsPlannedRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsRequestsExt requestsExtNew)
        {
            
            requestsExtNew.Fill();
            //DB.FillTrainingsRequestExt(requestsExtNew);
            if(requestsExtNew.Key!=null)
            {
                var resultRequestExt = InternalClasses.TrainingsRequestsExtDictionary[(int)requestsExtNew.Key];
                resultRequestExt.Request.RequestDate = DateTime.Now;
                resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
                resultRequestExt.Request.IdTrainingsRequestsStatus = 1;
                resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
                resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
                resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
                resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;
                resultRequestExt.Request.Company = requestsExtNew.Request.Company;
                resultRequestExt.Request.IdCustomer = requestsExtNew.Request.IdCustomer;
                resultRequestExt.Request.IdContact = requestsExtNew.Request.IdContact;
                resultRequestExt.Request.IdLegalEntity = requestsExtNew.Request.IdLegalEntity;

                resultRequestExt.SaveToDb(Request.LogonUserIdentity.Name);
                //DB.TrainingsRequestsExtInsert(resultRequestExt);
            }
            
            return RedirectToAction("TrainingsRequestSuccess", new { idContact = requestsExtNew.Request.IdContact });
        }

        public ActionResult TrainingsRequestSuccess(int idContact)
        {
            return View();
        }

        /// <summary>
        /// Частичное отображение расписания
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ActionResult TrainingsPlannedRequestSchedulePartial(int key)
        {
            var requestExt = InternalClasses.TrainingsRequestsExtDictionary[key];
            var scheduleId = requestExt.Request.IdTrainingsSchedule;
            if (scheduleId != null)
            {
                var schedulesCol = new TrainingsSchedulesCollection();
                var schedule = schedulesCol.GetItemById((int)scheduleId);
                
                //var schedule = DB.GetTrainingsSchedulebyId((int)scheduleId);)
                return PartialView(schedule);
            }
            return RedirectToAction("TrainingsSchedules");
        }
        
        //Частичное отображение участников расширенной заявки с возможностью редактирования списка

        //Используется во всех типах заявок при создании и редактировании
        
        /// <summary>
        /// таблица для изменения пользователей
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ActionResult TrainingsParticipantsPartial(int key)
        {
            var requestExt = InternalClasses.TrainingsRequestsExtDictionary[key];
            return PartialView(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsParticipants participantsNew, int key)
        {
            participantsNew.IdUser = Request.LogonUserIdentity.Name;
            if (participantsNew.IdTrainingsParticipantsStatus == 0)
                participantsNew.IdTrainingsParticipantsStatus = 2;
            var requestExt = InternalClasses.TrainingsRequestsExtDictionary[key];

            requestExt.AddParticipant(participantsNew);
            //DB.TrainingsParticipantsAdd(participantsNew, key);)
            
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsParticipants participantsEdit, int key)
        {
            var requestExt = InternalClasses.TrainingsRequestsExtDictionary[key];
            if (participantsEdit.IdTrainingsParticipantsStatus == 0)
                participantsEdit.IdTrainingsParticipantsStatus = 2;
            requestExt.UpdateParticipant(participantsEdit);
            //DB.TrainingsParticipantsEdit(participantsEdit, key);)
            
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TrainingsParticipantsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TrainingsParticipants participantsDel, int key)
        {
            var requestExt = InternalClasses.TrainingsRequestsExtDictionary[key];

            requestExt.DeleteParticipant(participantsDel);
            //DB.TrainingsParticipantsDel(participantsDel, key);)
            
            return PartialView("TrainingsParticipantsPartial", requestExt);
        }

        //------------------------

        #endregion

        #region Старый код
        
        //#region TrainingsRequestes

        ///// <summary>
        ///// создание новой плановой заявки
        ///// </summary>
        ///// <param name="scheduleId"></param>
        ///// <returns></returns>
        //public ActionResult TrainingsPlannedRequestCreate(int scheduleId)
        //{
        //    var requestExt = new TrainingsRequestsExt();
        //    requestExt.Request.IdCustomer = 0;
        //    requestExt.Request.IdTrainingsSchedule = scheduleId;

        //    int key = DB.TrainingsRequestsExtDictionary.Count;
        //    requestExt.Request.IdTrainingsRequest = key;

        //    DB.TrainingsRequestsExtDictionary.Add(key, requestExt);
        //    return View(requestExt);
        //}

        //public ActionResult TrainingsPlannedRequestCreatePartial(int key)
        //{
        //    var requestExt = DB.TrainingsRequestsExtDictionary[key];
        //    return PartialView(requestExt);
        //}

        //public ActionResult TrainingsPlannedRequestSchedulePartial(int key)
        //{
        //    var requestExt = DB.TrainingsRequestsExtDictionary[key];
        //    var scheduleId = requestExt.Request.IdTrainingsSchedule;
        //    if (scheduleId != null)
        //    {
        //        var schedule = DB.GetTrainingsSchedulebyId((int)scheduleId);
        //        return PartialView(schedule);
        //    }
        //    return RedirectToAction("TrainingsSchedules");
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TrainingsPlannedRequestCreatePartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsNew, int key)
        //{
        //    participantsNew.IdUser = Request.LogonUserIdentity.Name;
        //    participantsNew.IdTrainingsParticipantsStatus = 2;
        //    var requestExt = DB.TrainingsRequestsExtDictionary[key];
        //    DB.TrainingsParticipantsAdd(participantsNew, key);
        //    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TrainingsPlannedRequestCreatePartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
        //{
        //    var requestExt = DB.TrainingsRequestsExtDictionary[key];
        //    DB.TrainingsParticipantsDel(participantsDel, key);
        //    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TrainingsPlannedRequestCreatePartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsParticipants participantsDel, int key)
        //{
        //    var requestExt = DB.TrainingsRequestsExtDictionary[key];
        //    DB.TrainingsParticipantsEdit(participantsDel, key);
        //    return PartialView("TrainingsPlannedRequestCreatePartial", requestExt);
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TrainingsPlannedRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequestsExt requestsExtNew)
        //{
        //    if (requestsExtNew != null)
        //    {
        //        if (requestsExtNew.Request.ContactName == null)
        //            requestsExtNew.Request.ContactName = "";
        //        if (requestsExtNew.Request.ContactPhone == null)
        //            requestsExtNew.Request.ContactPhone = "";
        //        if (requestsExtNew.Request.ContactEmail == null)
        //            requestsExtNew.Request.ContactEmail = "";
        //        if (requestsExtNew.Request.Comments == null)
        //            requestsExtNew.Request.Comments = "";
        //    }
        //    var resultRequestExt = DB.TrainingsRequestsExtDictionary[requestsExtNew.Request.IdTrainingsRequest];
        //    resultRequestExt.Request.RequestDate = DateTime.Now;
        //    resultRequestExt.Request.IdUser = Request.LogonUserIdentity.Name;
        //    resultRequestExt.Request.IdTrainingsRequestsStatus = 1;
        //    resultRequestExt.Request.Company = requestsExtNew.Request.Company;
        //    resultRequestExt.Request.ContactName = requestsExtNew.Request.ContactName;
        //    resultRequestExt.Request.ContactPhone = requestsExtNew.Request.ContactPhone;
        //    resultRequestExt.Request.ContactEmail = requestsExtNew.Request.ContactEmail;
        //    resultRequestExt.Request.Comments = requestsExtNew.Request.Comments;

        //    //временная подстановка клиента: 
        //    resultRequestExt.Request.IdCustomer = 106656;


        //    DB.TrainingsRequestsExtInsert(resultRequestExt);
        //    return RedirectToAction("TrainingsSchedules");
        //}

        //#endregion
        
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //#region AddNewRequest

        //public ActionResult AddRequest(int id)
        //{
        //    var traningsRequestsExt = TempData["traningsRequestsExt"] as TraningsRequestsExt;
        //    if(traningsRequestsExt == null)
        //    {
        //        traningsRequestsExt = new TraningsRequestsExt();
        //    }
        //    TempData["traningsRequestsExt"] = traningsRequestsExt;
        //    return View(traningsRequestsExt);
        //}

        //public ActionResult AddRequestFirstTime(int id)
        //{
        //    TempData["traningsRequestsExt"] = null;
        //    var traningsRequestsExt = new TraningsRequestsExt();
        //    TempData["traningsRequestsExt"] = traningsRequestsExt;
        //    return View(traningsRequestsExt);
        //}

        //public ActionResult AddRequestSchedulesPartial(TraningsRequestsExt traningsRequestsExt, int id)
        //{
        //    return PartialView(new List<TrainingsSchedules> {DB.GetTrainingsScheduleById(id)});
        //}

        //public ActionResult AddRequestParticipantsPartial(int id)
        //{
        //    var traningsRequestsExt = TempData["traningsRequestsExt"] as TraningsRequestsExt;
        //    return PartialView("AddRequestParticipantsPartial", traningsRequestsExt);
        //}

        //[HttpPost]
        //public ActionResult AddRequestParticipantsPartial([ModelBinder(typeof(DevExpressEditorsBinder))] TraningsRequestsExt traningsRequestsExtNew, int id)
        //{
        //    var traningsRequestsExt = TempData["traningsRequestsExt"] as TraningsRequestsExt;
        //    traningsRequestsExtNew.ParticipantItem.IdUser = Request.LogonUserIdentity.Name.ToString();
        //    if (traningsRequestsExt == null)
        //    {
        //        traningsRequestsExt = traningsRequestsExtNew;
        //        traningsRequestsExt.ParticipantsList.Add(traningsRequestsExt.ParticipantItem);
        //        TempData["traningsRequestsExt"] = traningsRequestsExt;
        //        return RedirectToAction("AddRequest", "TC", new { id });
        //    }

        //    traningsRequestsExt.ParticipantsList.Add(traningsRequestsExtNew.ParticipantItem);
        //    TempData["traningsRequestsExt"] = traningsRequestsExt;
        //    return RedirectToAction("AddRequest", "TC", new { id });
        //}

        //public ActionResult AddRequestPartial(int id)
        //{
        //    var traningsRequestsExt = TempData["traningsRequestsExt"] as TraningsRequestsExt;
        //    if (traningsRequestsExt == null)
        //    {
        //        traningsRequestsExt = new TraningsRequestsExt();
        //    }
        //    TempData["traningsRequestsExt"] = traningsRequestsExt;
        //    return View(traningsRequestsExt);
        //}

        //[HttpPost]
        //public ActionResult AddRequestPartial([ModelBinder(typeof(DevExpressEditorsBinder))] TraningsRequestsExt resultRequest, int id)
        //{
        //    var traningsRequestsExt = TempData["traningsRequestsExt"] as TraningsRequestsExt;
        //    if (traningsRequestsExt == null)
        //    {
        //        return RedirectToAction("Index", "TC", new { id });
        //    }
        //    resultRequest.ParticipantsList = traningsRequestsExt.ParticipantsList;
        //    TempData["traningsRequestsExt"] = null;
        //    resultRequest.IdSchedule = id;
     
            

        //    TempData["RequestToConfirm"] = resultRequest;
        //    return RedirectToAction("ConfirmRequest");
        //}

        //public ActionResult ConfirmRequest()
        //{
        //    var requestToConfirm = TempData["RequestToConfirm"] as TraningsRequestsExt;
        //    TempData["RequestToConfirm"] = null;
        //    TempData["ConfirmedRequest"] = requestToConfirm;
        //    if (requestToConfirm != null)
        //    {
        //        var scheduleItem = DB.GetTrainingsScheduleById(requestToConfirm.IdSchedule);
        //        ViewData["ScheduleItem"] = new List<TrainingsSchedules> { scheduleItem };
        //    }
        //    return View(requestToConfirm);
        //}

        //[HttpPost]
        //public ActionResult ConfirmRequest(TraningsRequestsExt requests)
        //{
        //    var requestsExt = TempData["ConfirmedRequest"] as TraningsRequestsExt;
        //    if (requestsExt != null)
        //    {

        //        DB.TraningsRequestsExtInsert(requestsExt);
                
        //        TempData["ConfirmedRequest"] = null;
        //        return RedirectToAction("Index");
        //    }
        //    TempData["ConfirmedRequest"] = null;
        //    return RedirectToAction("Index");
        //}

        //#endregion

        //public ActionResult GridViewPartCallBack([ModelBinder(typeof(DevExpressEditorsBinder))] TrainingsRequests newRequestItem)
        //{
        //   if(newRequestItem==null)
        //   {
        //       newRequestItem = ViewData["newRequestItem"] as TrainingsRequests;
        //       //if (newRequestItem == null)
        //       //{
        //       //    newRequestItem = new TrainingsRequests();
        //       //}
        //   }
        //    return PartialView("GridViewParticipants", newRequestItem);
        //}

        //public ActionResult ParticipantsAdd( [ModelBinder(typeof(DevExpressEditorsBinder))] TraningsParticipants newParticipantItem)
        //{
        //    //if(newRequestItem!=null)
        //    //{
        //    //    if (newParticipantItem!=null)
        //    //        newRequestItem.TraningsParticipants.Add(newParticipantItem);
        //    //}
        //    return PartialView("GridViewParticipants");//, newRequestItem);
        //}

        #endregion
    }
}
